package cn.pugle.base.uri_encode;

import org.apache.http.NameValuePair;
import org.apache.http.entity.StringEntity;
import org.apache.http.protocol.HTTP;

import java.io.UnsupportedEncodingException;
import java.util.List;

public class FormEntity extends StringEntity {

	public FormEntity(final List<? extends NameValuePair> parameters,
                      final String encoding) throws UnsupportedEncodingException {
		super(converToString(parameters));
//		setContentType(URLEncodedUtils.CONTENT_TYPE + HTTP.CHARSET_PARAM + (encoding != null ? encoding : HTTP.DEFAULT_CONTENT_CHARSET));
	}

	private static String converToString(
			List<? extends NameValuePair> parameters) {
		StringBuilder sb = new StringBuilder("");
		for (NameValuePair nameValuePair : parameters) {
			sb.append(nameValuePair + "&");
		}
		String param = sb.deleteCharAt(sb.length() - 1).toString();
		return param;
	}

	public FormEntity(final List<? extends NameValuePair> parameters)
			throws UnsupportedEncodingException {
		this(parameters, HTTP.DEFAULT_CONTENT_CHARSET);
	}
}
